//load setting from google or just set as default
chrome.storage.sync.get("suffix",function (data) {
    if(typeof data != 'undefined' && Object.keys(data).length  > 0){
        suffixList = JSON.parse(data.suffix);
        console.info("load suffix setting from server");
    }else{
        console.info("load suffix setting by default");
        var suffixListJson = JSON.stringify(suffixList)
        chrome.storage.sync.set({"suffix":suffixListJson},function(callback) {

        })
    }
})

chrome.storage.sync.get("contentType",function (data) {
    if(typeof data != 'undefined' && Object.keys(data).length  > 0){
        contentTypeList = JSON.parse(data.contentType);
        console.info("load contentType setting from server");
    }else{
        console.info("load contentType setting by default");
        var contentTypeListJson = JSON.stringify(contentTypeList)
        chrome.storage.sync.set({"contentType":contentTypeListJson},function(callback) {

        })
    }
})

/*mediaList structure
  tadId:对应tag
  name:文件名
  suffix:格式
  size：大小
  url:url
  responseHeader:
 */
var mediaList;
if(typeof mediaList === 'undefined'){ mediaList = new Array()};


//filter types设置为media 测试youtube aiqiyi 无效。故改用文件后缀名 方案。
chrome.webRequest.onResponseStarted.addListener(
    function(data){
        var url =data.url;
        console.log(url);
        var fileName = getfileNameByUrl(removeUrlParams(url));
        var suffix = getSuffixByFileName(fileName)
        fileName = fileName.split(".")[0];
        var size = getResponseHeadersValue("content-length",data);
        var contentType =  getResponseHeadersValue("content-type",data);
        size = size == null ? 0 : size / 1024;
        //url tabId
        if(mediaFilter(suffix,size,contentType)){
            if(mediaList[data.tabId] == undefined){mediaList[data.tabId] = new Array()}
            //check repeat
            for(var i=0 ;i<mediaList[data.tabId].length;i++){
                if(mediaList[data.tabId][i] != undefined){
                    if(mediaList[data.tabId][i].url == url){
                        return;
                    }
                }
            }
            var info = {tabId:data.tabId,name:fileName,suffix:suffix,size:size
                ,url:url,headers:data.responseHeaders};
            mediaList[data.tabId].push(info);
            chrome.browserAction.setBadgeText({text: ""+mediaList[data.tabId].length,tabId:data.tabId});
            chrome.runtime.sendMessage(info);
        }

    },
    {urls: ["http://*/*", "https://*/*"]},
    ["responseHeaders"]
);

function getResponseHeadersValue(name, data){
    name = name.toLowerCase();
    for (var i = 0; i<data.responseHeaders.length; i++) {
        if (data.responseHeaders[i].name.toLowerCase() == name) {
            return data.responseHeaders[i].value.toLowerCase();
        }
    }
    return null;
}

function removeUrlParams(url) {
    //去除锚点
    url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
    //去除参数
    url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
    return url;
}

function getfileNameByUrl(url) {
    //取文件名
    url = url.substring(url.lastIndexOf("/") + 1, url.length);
    return url;
}

function getSuffixByFileName(fileName) {
    var indexOfLastDot = fileName.lastIndexOf(".");
    if(indexOfLastDot > 0){
        return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
    }else{
        return null;
    }
}

function mediaFilter(suffix,size,contentType) {
    if(!suffix)return false;
    suffix = suffix.toLowerCase();
    if(contentType != null){
        contentType = contentType.toLowerCase();
        for(var k = 0; k<contentTypeList.length;k++){
            console.log("rp:"+contentType+" cp:"+contentTypeList[k]+" r:" +contentType.indexOf(contentTypeList[k]));
            if(contentType.indexOf(contentTypeList[k]) != -1){
                return true;
            }
        }
    }
    for(var i = 0; i<suffixList.length; i++) {
        if(suffix == suffixList[i].suffix){
            if(size >= suffixList[i].size){
                return true;
            }
        }
    }
    return false;
}

chrome.tabs.onUpdated.addListener( function( tabId, changeInfo ){
    if(changeInfo.status=="loading")
    {
            clearTabInfo(tabId);
    }
});

chrome.tabs.onRemoved.addListener( function( tabId ){
    clearTabInfo(tabId);
} );

function clearTabInfo(tabId) {
    if(mediaList[tabId]) {
        delete mediaList[tabId];
    }
    chrome.browserAction.setBadgeText({text: "",tabId:tabId});
}